#include <string>
#include <kvs/AVSField>
#include <kvs/ValueArray>
#include <kvs/Type>
#include <kvs/Math>
#include <kvs/Vector3>
#include <kvs/ColorImage>


int main( int argc, char** argv )
{
    std::string filename( argv[1] );
    kvs::AVSField fld( filename );
    fld.print( std::cout );

    kvs::Vector3ui dim = fld.dim();
    kvs::ValueArray<kvs::UInt8> values = fld.values().asValueArray<kvs::UInt8>();

    kvs::ValueArray<kvs::UInt16> counter( dim.y() * dim.z() ); counter.fill(0);
    kvs::UInt16 max = 0;
    for ( size_t i = 0; i < dim.x(); i++ )
    {
        for ( size_t k = 0; k < dim.z(); k++ )
        {
            for ( size_t j = 0; j < dim.y(); j++ )
            {
                if ( values[ k * dim.x() * dim.y() + j * dim.x() + i ] > 0 )
                {
                    counter[ k * dim.y() + j ]++;
                    max = kvs::Math::Max( max, counter[ k * dim.y() + j ] );
                }
            }
        }
    }

    kvs::ValueArray<kvs::UInt8> pixels( dim.y() * dim.z() * 3 );
    for ( size_t i = 0; i < dim.y() * dim.z(); i++ )
    {
        int p = kvs::Math::Round( 255.0f * counter[i] / max );
        pixels[ 3 * i + 0 ] = p;
        pixels[ 3 * i + 1 ] = p;
        pixels[ 3 * i + 2 ] = p;
    }

    kvs::ColorImage image( dim.y(), dim.z(), pixels );
    image.write("output.bmp");

    return 0;
}
